package com.cn.shuangzi;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Build;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.cn.shuangzi.activity.SZInterfaceActivity;
import com.cn.shuangzi.util.SZFileUtil;
import com.cn.shuangzi.util.SZValidatorUtil;

import java.net.URISyntaxException;


public abstract class SZBaseWebActivity extends SZBaseActivity implements SZInterfaceActivity {
    public WebView webView;
    public ProgressBar webVBar;
    public WebSettings webSettings;
    private String url;
    private boolean isError;
    @Override
    protected int onGetChildView() {
        return R.layout.activity_base_web;
    }

    @Override
    protected void onBindChildViews() {
        webView = findViewById(R.id.webView);
        webVBar = findViewById(R.id.webVBar);
    }

    @Override
    protected void onBindChildListeners() {
        getTxtTitleLeft().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        getImgLeft().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    @Override
    protected void onChildViewCreated() {
        onChildViewCreatedPre();
        showBackImgLeft(getBackImgLeft());
        setTxtTitleLeft(R.string.txt_close);
        url = getStringExtra();
        if (SZValidatorUtil.isValidString(url)) {
            initWebViewSetting();
            webView.loadUrl(url);
        } else {
            finish();
        }
    }

    @Override
    protected void onReloadData(boolean isRefresh) {
        webView.reload();
    }

    private void initWebViewSetting() {
        if(!isShowLoadBarMode()) {
            webVBar.setMax(100);
        }
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if(isShowLoadBarMode()){
                    showBarTransparentStyle();
                }else {
                    webVBar.setVisibility(View.VISIBLE);
                    webVBar.setProgress(newProgress);
                }
                if (newProgress >= 100) {
                    if(isShowLoadBarMode()){
                        closeBar();
                    }else {
                        webVBar.setVisibility(View.GONE);
                    }
                }
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!shouldOverrideUrlLoadingByApp(url)) {
                    if(!url.equals(webView.getUrl())) {
                        webView.loadUrl(url);
                        return true;
                    }
                }
                return false;
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if(isError){
                    isShowError(true);
                }else{
                    isShowContent(true);
                    if(isChangeTitleWithUrl()) {
                        setTitleTxt(view.getTitle());
                    }
                }
                isError = false;
            }
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                isError = true;
            }
        });
        webSettings = webView.getSettings();
        initWebSetting();
        webView.setBackgroundColor(0);
    }

    private void initWebSetting() {
        webSettings.setJavaScriptEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            webSettings.setAllowUniversalAccessFromFileURLs(true);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webSettings.setDomStorageEnabled(true);    //开启DOM形式存储
        webSettings.setDatabaseEnabled(true);   //开启数据库形式存储

        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setTextZoom(100);
        webSettings.setAllowFileAccess(true);

        if(isOpenCacheMode()) {
            webSettings.setAppCachePath(SZFileUtil.getInstance().getCacheFile().getAbsolutePath());
            webSettings.setAppCacheEnabled(true);  //开启缓存功能
            webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);      //缓存模式
//            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);      //缓存模式
        }else{
            webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        }
    }
    /**
     * 根据url的scheme处理跳转第三方app的业务
     */
    private boolean shouldOverrideUrlLoadingByApp(String url) {
        if (url.startsWith("http") || url.startsWith("https") || url.startsWith("ftp")) {
            //不处理http, https, ftp的请求
            return false;
        }
        Intent intent;
        try {
            intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
        } catch (URISyntaxException e) {
            return false;
        }
        intent.setComponent(null);
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
        return true;
    }
    @Override
    protected void onPause() {
        super.onPause();
        if (webView != null) {
            webView.onPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (webView != null) {
            webView.onResume();
        }
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(webView!=null){
            webView.stopLoading();
            webView.destroy();
        }
    }
    public abstract boolean isShowLoadBarMode();
    public abstract boolean isChangeTitleWithUrl();
    public abstract boolean isOpenCacheMode();
}
